<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖动</title>
    <link rel="shortcut icon" href="../lib/image/favicon.ico" type="image/x-icon">
    <link rel="stylesheet" href="../lib/css/all.css">

</head>
<style>

    .box {
        width: 300px;
        height: 300px;
        background-color: aquamarine;
        position: absolute;
    }
</style>

<body>
    <div id="app">
        <div class="box">

        </div>
    </div>
    <script>
        window.onload = function () {
            var div = document.getElementsByClassName("box")[0];
            //1 div.onmousedown
            //2 document.onmousemove
            //3 document.onmouseup
            // var isDrag= false;
            var distanceX, distanceY;
            //按下鼠标时，定义事件
            div.onmousedown = function (evt) {
                evt = evt || window.event;
                isDrag = true;
                //console.log("isDrag:"+isDrag);
                //保存鼠标相对于div的偏移量
                distanceX = evt.offsetX;
                distanceY = evt.offsetY;
                // 按下鼠标时，定义document的移动事件
                document.onmousemove = function (evt) {
                    evt = evt || window.event;
                    console.log(isDrag + " onmousemove");
                    // if(isDrag){
                    // div.style.left= evt.clientX- distanceX+"px";
                    // div.style.top = evt.clientY- distanceY+"px";
                    var divLeft = evt.clientX - distanceX;
                    var divTop = evt.clientY - distanceY;
                    var maxLeft = document.documentElement.clientWidth - div.offsetWidth;
                    var maxTop = document.documentElement.clientHeight - div.offsetHeight;
                    //console.log(document.documentElement.clientHeight);
                    if (divLeft < 0) {
                        divLeft = 0;
                    }
                    if (divTop < 0) {
                        divTop = 0;
                    }
                    if (divLeft > maxLeft) {
                        divLeft = maxLeft;
                    }
                    if (divTop > maxTop) {
                        divTop = maxTop;
                    }

                    div.style.left = divLeft + "px";
                    div.style.top = divTop + "px";
                    // }
                    return false;
                }
                //按下鼠标时，定义document的鼠标弹起事件
                document.onmouseup = function () {
                    // isDrag =false;
                    // console.log(isDrag + " onmouseup");
                    document.onmousemove = null;
                    document.onmouseup = null;
                }
            }

        }
    </script>
</body>

</html>